package com.ruoyi.framework.security.provider;

import com.ruoyi.framework.security.token.ClientUserAuthToken;
import com.ruoyi.framework.web.service.ClientUserDetailsServiceImpl;
import com.ruoyi.system.domian.jpa.CdUserJpa;
import com.ruoyi.system.domian.service.CdUserService;
import com.ruoyi.common.core.domain.model.CdUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.string.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;

/**
 * @author Dale Mao    ---多多 Email:453918229@qq.com
 * @description ClientUserAuthenticationProvider
 * @date 2021-01-27 17:50
 */
public class ClientUserAuthenticationProvider  implements AuthenticationProvider {

    @Autowired
    CdUserService cdUserService;

    @Autowired
    ClientUserDetailsServiceImpl clientUserDetailsService;


    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {

        System.out.println("进入了提供器");
        //这个authentication就是SmsCodeAuthenticationToken
        ClientUserAuthToken authenticationToken = (ClientUserAuthToken) authentication;

        //校验手机号
        UserDetails user = clientUserDetailsService.loadUserByUsername((String) authenticationToken.getPrincipal());
        if (user == null) {
            throw new InternalAuthenticationServiceException("无法获取用户信息");
        }

        //这时候已经认证成功了
        ClientUserAuthToken authenticationResult = new ClientUserAuthToken(user, user.getAuthorities());
        authenticationResult.setDetails(authenticationToken.getDetails());

        return authenticationResult;

    }

    @Override
    public boolean supports(Class<?> aClass) {
        return aClass.equals(ClientUserAuthToken.class);
    }
}
